<?php
declare (strict_types = 1);

namespace app\controller\Auth;

use app\BaseController;
use app\model\User;
use think\Request;
use Firebase\JWT\JWT;

class Login extends BaseController
{
    /**
     * 用户登录
     */
    public function login(Request $request)
    {
        $data = $request->only(['username', 'password']);
        
        // 验证数据
        $this->validate($data, [
            'username' => 'require',
            'password' => 'require'
        ], [
            'username.require' => '用户名不能为空',
            'password.require' => '密码不能为空'
        ]);

        // 查找用户
        $user = User::findByUsername($data['username']);
        
        if (!$user) {
            return $this->error('用户名或密码错误');
        }
        
        // 验证密码
        if (!$user->verifyPassword($data['password'])) {
            return $this->error('用户名或密码错误');
        }
        
        // 检查用户状态
        if (!$user->status) {
            return $this->error('账户已被禁用');
        }
        
        // 更新登录信息
        $user->updateLoginInfo($request->ip());
        
        // 生成JWT token
        $payload = [
            'user_id' => $user->id,
            'username' => $user->username,
            'exp' => time() + config('jwt.expire')
        ];
        
        $token = JWT::encode($payload, config('jwt.secret'), config('jwt.algo'));
        
        return $this->success([
            'token' => $token,
            'user_info' => $user->getUserInfo()
        ], '登录成功');
    }

    /**
     * 用户登出
     */
    public function logout()
    {
        return $this->success(null, '登出成功');
    }

    /**
     * 获取用户信息
     */
    public function profile(Request $request)
    {
        $user = $request->user;
        
        // 检查用户信息是否存在
        if (!$user || !isset($user['user_id'])) {
            return $this->error('用户信息无效', 401);
        }
        
        // 从数据库获取最新用户信息
        $userModel = User::find($user['user_id']);
        
        if (!$userModel) {
            return $this->error('用户不存在');
        }
        
        return $this->success($userModel->getUserInfo());
    }
    
    /**
     * 刷新Token
     */
    public function refresh(Request $request)
    {
        $user = $request->user;
        
        // 生成新的JWT token
        $payload = [
            'user_id' => $user['user_id'],
            'username' => $user['username'],
            'exp' => time() + config('jwt.expire')
        ];
        
        $token = JWT::encode($payload, config('jwt.secret'), config('jwt.algo'));
        
        return $this->success([
            'token' => $token
        ], 'Token刷新成功');
    }
} 